<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-7-11
 * Time: 10:05
 */
namespace wxpay;
use think\Session;

class GetToken
{
    protected static $AppID; //appid
    protected static $AppSecret;

    public function __construct($AppID='wx1cdeeacadb389271',$AppSecret='afcf2fa88830217cd1ba8233594e41f0')
    {
        self::$AppID = $AppID;
        self::$AppSecret = $AppSecret;
    }

    /**
     * 请求接口获取token
     */
    public static function request()
    {
        $old =Session::get('token','index');
        $alive = Session::get('alive','index') ? Session::get('alive','index') : 0; //获取第一次获取tocken的时间
        $alive = $alive + 7000; //加上7000s

        if (isset($old) && ($alive > time())) {
            return $old;
        }

        //curl请求接口
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.self::$AppID.'&secret='.self::$AppSecret;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data = json_decode(curl_exec($ch));
        curl_close($ch);
        Session::set('token',$data->access_token,'index');
        Session::set('alive',time(),'index');

        return $data->access_token;
    }

}